<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>重力感应贪吃蛇</title>
</head>
<body>
<div style='margin:0 auto;width:0px;height:0px;overflow:hidden;'>
<img src="./img/1.png" width='700'>
</div>
<canvas id="can" width="800" height="800" style="background:Black;z-index:-1;" ></canvas>
<script>
		var map = document.getElementById("can");
		var ctx = map.getContext("2d");
		var mwidth = document.documentElement.clientWidth;
		var mheight = document.documentElement.clientHeight;
		//定义上下左右,根据keycode定义
		var D_LEFT = 1, D_UP = 2, D_RIGHT = 3, D_DOWN = 4;
		var PER_SIZE = mwidth > mheight ? Math.floor(mheight / 20) : Math
				.floor(mwidth / 20);
		var MAP_WITDH = Math.floor((mwidth - 10) / PER_SIZE) * PER_SIZE;
		var MAP_HEIGHT = Math.floor((mheight - 10) / PER_SIZE) * PER_SIZE;
		var BEGIN_HEAD_X = 4 * PER_SIZE;
		var BEGIN_HEAD_Y = 3 * PER_SIZE;
		var FRESHTIME = 400;//刷新时间，时间越大，速度越慢

		map.setAttribute("width", MAP_WITDH);
		map.setAttribute("height", MAP_HEIGHT);

		//snake类
		function Snake() {
			this.body = [];
			this.direction = D_RIGHT;
		}

		function Point(x, y) {
			this.x = x;
			this.y = y;
		}

		//初始化snake
		var snake = new Snake();
		var p1 = new Point(BEGIN_HEAD_X, BEGIN_HEAD_Y);
		var p2 = new Point(BEGIN_HEAD_X - PER_SIZE, BEGIN_HEAD_Y);
		snake.body = [ p1, p2 ];
		//var head = snake.body[0];

		//初始化food
		var food;
		createFood();

		//定义标志变量
		var isEat = false;
		var isMove = false;
		var nextMove = 0;

		document.onkeydown = function(e) {
			//keycode:左37，上38，右39，下40
			var key = e.keyCode - 36;
			keydown(key);
		}

		if (window.DeviceOrientationEvent && 'ontouchstart' in window) {
			window.addEventListener('deviceorientation', function(e) {
				var alpha = e.alpha, //垂直于屏幕的轴 0 ~ 360
				beta = e.beta, //横向 X 轴 -180 ~ 180
				gamma = e.gamma; //纵向 Y 轴 -90 ~ 90
				if (Math.abs(gamma) > Math.abs(beta)) {
					if (gamma > 15 && gamma < 50) {
						keydown(D_RIGHT);
					} else if (gamma > -50 && gamma < -15) {
						keydown(D_LEFT);
					}
				} else {
					if (beta > 15 && beta < 50) {
						keydown(D_DOWN);
					} else if (beta > -50 && beta < -15) {
						keydown(D_UP);
					}
				}

			}, false);
		}

		function keydown(key) {
			if (key > 0 && key < 5) {
				if (((key == D_UP || key == D_DOWN) && (snake.direction == D_LEFT || snake.direction == D_RIGHT))
						|| ((key == D_LEFT || key == D_RIGHT) && (snake.direction == D_UP || snake.direction == D_DOWN))) {
					if (isMove) {
						snake.direction = key;
						isMove = false;
						console.info('key:' + key);
					} else {
						nextMove = key;
						console.info('nextMove:' + nextMove);
					}

				}
			}
		}

		!function() {
			if (isGameOver()) {
				if (confirm('哈哈哈，you带了，是否重来？') == 1) {
					location.reload(false);
				} else {
					return;
				}

				//return console.error('snake.direction:'+snake.direction+';nextMove:'+nextMove);
			}
			if (eat()) {
				/* eatTip(); */
				//隐藏上一个food
				draw(food, 'Black');
				//新增下一个food
				createFood();
			}
			move();
			setTimeout(arguments.callee, FRESHTIME);
		}();

		//画笔
		function draw(p, color) {
			ctx.fillStyle = color;
			ctx.fillRect(p.x, p.y, PER_SIZE - 2, PER_SIZE - 2);
		}

		//移动
		function move() {
			var p = getNewHeadPoint();
			snake.body.unshift(p);
			if (isEat) {
				isEat = false;
			} else {
				var p_old = snake.body.pop();
				draw(p_old, 'Black');
			}
			drawSnake();
			isMove = true;
			if (nextMove != 0) {
				snake.direction = nextMove;
				nextMove = 0;
				isMove = false;
			}
		}

		//
		function getNewHeadPoint() {
			var head = snake.body[0];
			var p;
			switch (snake.direction) {
			case D_UP:
				p = new Point(head.x, head.y - PER_SIZE);
				break;
			case D_DOWN:
				p = new Point(head.x, head.y + PER_SIZE);
				break;
			case D_LEFT:
				p = new Point(head.x - PER_SIZE, head.y);
				break;
			case D_RIGHT:
				p = new Point(head.x + PER_SIZE, head.y);
				break;
			}
			return p;
		}

		//画蛇
		function drawSnake() {
			for ( var i = 0; i < snake.body.length; i++) {
				if (i == 0) {
					draw(snake.body[i], 'Yellow');
				} else {
					draw(snake.body[i], 'Lime');
				}

			}
		}

		//是否游戏结束
		function isGameOver() {
			var head = snake.body[0];
			//碰到边界
			if (((head.x + PER_SIZE) >= MAP_WITDH && snake.direction == D_RIGHT)
					|| (head.x <= 0 && snake.direction == D_LEFT)
					|| ((head.y + PER_SIZE) >= MAP_HEIGHT && snake.direction == D_DOWN)
					|| (head.y <= 0 && snake.direction == D_UP)) {
				return true;
			}
			//碰到自己身体，第一个为头
			for ( var i = 1; i < snake.body.length; i++) {
				var bodyx = snake.body[i].x;
				var bodyy = snake.body[i].y;
				if (bodyx == head.x) {
					if (snake.direction == D_UP && bodyy + PER_SIZE == head.y) {
						// alert('Game over!'+bodyx+';'+bodyy+';'+head.x+';'+head.y); 
						return true;
					}
					if (snake.direction == D_DOWN && bodyy - PER_SIZE == head.y) {
						// alert('Game over!'+bodyx+';'+bodyy+';'+head.x+';'+head.y);
						return true;
					}
				}
				if (bodyy == head.y) {
					if (snake.direction == D_LEFT && bodyx + PER_SIZE == head.x) {
						// alert('Game over!'+bodyx+';'+bodyy+';'+head.x+';'+head.y);
						return true;
					}
					if (snake.direction == D_RIGHT
							&& bodyx - PER_SIZE == head.x) {
						// alert('Game over!'+bodyx+';'+bodyy+';'+head.x+';'+head.y); 
						return true;
					}
				}
			}
			return false;
		}

		//判断是否吃到了
		function eat() {
			var head = snake.body[0];
			if (head.x == food.x && head.y == food.y) {
				isEat = true;
				return isEat;
			}
			return false;
		}

		//获取下一个food点
		function getFoodPoint() {
			var foodx = Math.floor(Math.random() * MAP_WITDH / PER_SIZE)
					* PER_SIZE;
			var foody = Math.floor(Math.random() * MAP_HEIGHT / PER_SIZE)
					* PER_SIZE;
			if (foodx >= MAP_WITDH)
				foodx = foodx - PER_SIZE;
			if (foody >= MAP_WITDH)
				foody = foody - PER_SIZE;
			for ( var i = 0; i < snake.body.length; i++) {
				if (snake.body[i].x == foodx && snake.body[i].y == foody) {
					return getFoodPoint();
				}
			}
			return new Point(foodx, foody);
		}

		//新增一个food
		function createFood() {
			food = getFoodPoint();
			if ((food.x + PER_SIZE) > MAP_WITDH || food.x < 0
					|| (food.y + PER_SIZE) > MAP_HEIGHT || food.y < 0) {
				console.error('x:' + food.x + ';y:' + food.y);
			} else {
				console.info('x:' + food.x + ';y:' + food.y);
			}

			draw(food, 'Red');
		}
	</script>
	<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
	<script type="text/javascript" src="https://vast-inlet-75928.herokuapp.com/js/stat.js"></script>
</body>
</html>
